package vn.ikame.android.chuyenay;

import java.io.IOException;

import vn.ikame.android.adapter.ListQuestionAdapter;
import vn.ikame.android.object.Var;
import vn.ikame.android.plugin.BaseActivity;
import vn.ikame.android.plugin.ChatActivity;
import vn.ikame.android.plugin.CustomDialog;
import vn.ikame.android.utils.CStore;
import vn.ikame.android.utils.CommonUtils;
import vn.ikame.android.utils.XMLParser;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.loopj.android.image.SmartImageView;

public class QuestionList extends BaseActivity implements OnClickListener{
	public ViewPager viewPager;
	public QuestionPagerAdapter pagerAdapter;
	public OnPageChangeListener onPageChange;
	public ProgressDialog mProgressDialog;
	public AdView adView;
	public AlertDialog.Builder alert;
	
	public static boolean trackGA = true;
	public static GoogleAnalyticsTracker generalTracker;
	public static GoogleAnalyticsTracker detailsTracker;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.questionlist);
        Var.store = new CStore(this);
        
        if (trackGA) {
			generalTracker = GoogleAnalyticsTracker.getInstance();
			generalTracker.startNewSession("UA-33515341-2",
					getApplicationContext());
			generalTracker.trackTransactions();
			generalTracker.trackPageView("ChuyenAy_Android");
			generalTracker.dispatch();
			trackGA = false;

			detailsTracker = GoogleAnalyticsTracker.getInstance();
			detailsTracker.startNewSession("UA-33515341-8",
					getApplicationContext());
			detailsTracker.trackTransactions();
			detailsTracker.trackPageView("ChuyenAy_Android");
			detailsTracker.dispatch();
			
			if (!Var.store.isInstall()) {
				createAboutMessage();
				Var.store.setInstall(true);

				generalTracker.trackPageView("ChuyenAy_Android_Install");
				generalTracker.dispatch();

				detailsTracker.trackPageView("ChuyenAy_Android_Install");
				detailsTracker.dispatch();
			}
		}
        
        
        LinearLayout lLinLayout = (LinearLayout) findViewById(R.id.mainlayout1);
		RelativeLayout.LayoutParams adParams2 = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		adParams2.addRule(RelativeLayout.ALIGN_BOTTOM);
		adParams2.addRule(RelativeLayout.CENTER_IN_PARENT);

		adView = new AdView(this, AdSize.SMART_BANNER, "a15058b26fd002b");
		adView.loadAd(new AdRequest());
		lLinLayout.addView(adView, adParams2);
        
        ((ImageButton) findViewById(R.id.bt_ay)).setOnClickListener(this);
		((ImageButton) findViewById(R.id.bt_adam)).setOnClickListener(this);
		((ImageButton) findViewById(R.id.bt_eva)).setOnClickListener(this);
        
        pagerAdapter = new QuestionPagerAdapter();
		viewPager = (ViewPager) findViewById(R.id.awesomepager);
		viewPager.setAdapter(pagerAdapter);
		onPageChange = new OnPageChangeListener();
		viewPager.setOnPageChangeListener(onPageChange); 
		
		Var.cateID = Var.store.getCateID();
		

		LinearLayout ll = (LinearLayout) findViewById(R.id.title);
		switch (Var.cateID) {
		case Var.CHUYEN_AY:
			ll.setBackgroundResource(R.drawable.titlephongdoi);
			((ImageButton) findViewById(R.id.bt_ay)).setVisibility(View.GONE);
			((ImageButton) findViewById(R.id.bt_adam)).setVisibility(View.VISIBLE);
			((ImageButton) findViewById(R.id.bt_eva)).setVisibility(View.VISIBLE);
			
			if(Var.listChuyenAy.size() < 3){
				initQuestionList(Var.cateID);
			}
			break;
		case Var.CHUYEN_ADAM:
			ll.setBackgroundResource(R.drawable.titlephongnam);
			((ImageButton) findViewById(R.id.bt_ay)).setVisibility(View.VISIBLE);
			((ImageButton) findViewById(R.id.bt_adam)).setVisibility(View.GONE);
			((ImageButton) findViewById(R.id.bt_eva)).setVisibility(View.VISIBLE);
			
			if(Var.listChuyenAdam.size() < 3){
				initQuestionList(Var.cateID);
			}
			break;
		case Var.CHUYEN_EVA:
			ll.setBackgroundResource(R.drawable.titlephongnu);
			((ImageButton) findViewById(R.id.bt_ay)).setVisibility(View.VISIBLE);
			((ImageButton) findViewById(R.id.bt_adam)).setVisibility(View.VISIBLE);
			((ImageButton) findViewById(R.id.bt_eva)).setVisibility(View.GONE);
			
			if(Var.listChuyenEva.size() < 3){
				initQuestionList(Var.cateID);
			}
			break;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu_question, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.chat:
//			CategoryList.this.finish();
			startActivity(new Intent(QuestionList.this, ChatActivity.class));
			break;
		case R.id.moregame:
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse("market://search?q=ikame"));
			startActivity(intent);
			break;
		case R.id.rateapp:
			Intent intent1 = new Intent(Intent.ACTION_VIEW);
			intent1.setData(Uri.parse("market://details?id=" + Var.APP_PACKAGE));
			startActivity(intent1);
			break;
		case R.id.share:
			
			Intent sharingIntent = new Intent(Intent.ACTION_SEND);
			sharingIntent.setType("text/plain");
			sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id="  + Var.APP_PACKAGE);
			sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Chuyện 'ấy'");
			startActivity(Intent.createChooser(sharingIntent, "Share using"));
			break;
		case R.id.about:
			createAboutMessage();
			break;

		}
		return true;
	}

	
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.bt_adam:
			Var.cateID = Var.CHUYEN_ADAM;
			viewPager.setCurrentItem(Var.cateID);
			break;
		case R.id.bt_eva:
			Var.cateID = Var.CHUYEN_EVA;
			viewPager.setCurrentItem(Var.cateID);
			break;
		case R.id.bt_ay:
			Var.cateID = Var.CHUYEN_AY;
			viewPager.setCurrentItem(Var.cateID);
			break;
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			createExitMessage();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	public void createExitMessage() {
		alert = new AlertDialog.Builder(this);
		alert.setMessage("Bạn có thực sự muốn thoát ứng dụng?");
		alert.setPositiveButton("Có",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						if(noti.getType() == 3 && !noti.isShow()){
							createNotificationAlert();
						} else {
							QuestionList.this.finish();
							System.gc();
							android.os.Process.killProcess(android.os.Process
									.myPid());
						}
					}
				});

		alert.setNegativeButton("Không",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						
					}
				});
		alert.setCancelable(true);
		alert.show();
	}
	
	public void createNotificationAlert(){
		if(noti.isShow()){
			return;
		}
		
		try {
			System.out.println("Show Notify");
			noti.setShow(true);
			noti.setAlert(new CustomDialog.Builder(this));
			noti.getAlert().setMessage(noti.getContent());
			
			SmartImageView image = (SmartImageView)noti.getAlert().getView().findViewById(R.id.icon);
			image.setImageUrl(noti.getIconLink());
			
			TextView text = (TextView)noti.getAlert().getView().findViewById(R.id.name);
			text.setText(noti.getName());
			
			if(!noti.getAppLink().equals("")){
				noti.getAlert().setPositiveButton("Xem app", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setData(Uri.parse(noti.getAppLink()));
						startActivity(intent);
					}
				});
			}

			noti.getAlert().setNegativeButton("Thoát", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					dialog.dismiss();
					finish();
					System.gc();
					android.os.Process.killProcess(android.os.Process.myPid());
				}
			});
			noti.getAlert().setCancelable(true);
			noti.getAlert().show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public class QuestionPagerAdapter extends PagerAdapter {
		public QuestionPagerAdapter() {
		}

		@Override
		public int getCount() {
			return 3;
		}

		@Override
		public Object instantiateItem(View collection, int pageViewPos) {
			View view;
			LayoutInflater vi = (LayoutInflater) QuestionList.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = vi.inflate(R.layout.pager_question, null);
			
			//List View
			ListQuestionAdapter arrayAdapter = null;
			
			switch (pageViewPos) {
			case Var.CHUYEN_AY:
				((LinearLayout)view.findViewById(R.id.bgphong)).setBackgroundResource(R.drawable.bgphong);
				arrayAdapter = new ListQuestionAdapter(QuestionList.this,R.layout.list, Var.listChuyenAy, pageViewPos);
				break;
			case Var.CHUYEN_ADAM:
				((LinearLayout)view.findViewById(R.id.bgphong)).setBackgroundResource(R.drawable.bgnam);
				arrayAdapter = new ListQuestionAdapter(QuestionList.this,R.layout.list, Var.listChuyenAdam, pageViewPos);
				break;
			case Var.CHUYEN_EVA:
				((LinearLayout)view.findViewById(R.id.bgphong)).setBackgroundResource(R.drawable.bgnu);
				arrayAdapter = new ListQuestionAdapter(QuestionList.this,R.layout.list, Var.listChuyenEva, pageViewPos);
				break;
			}
			ListView list = (ListView) view.findViewById(R.id.listview);
			list.setAdapter(arrayAdapter);
			list.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {

					Var.itemID = position;
					startActivity(new Intent(QuestionList.this, Answer.class));
				}
			});
			

			((ViewPager) collection).addView(view, 0);

			return view;
		}

		/**
		 * Remove a page for the given position. The adapter is responsible for
		 * removing the view from its container, although it only must ensure
		 * this is done by the time it returns from {@link #finishUpdate()}.
		 * 
		 * @param container
		 *            The containing View from which the page will be removed.
		 * @param position
		 *            The page position to be removed.
		 * @param object
		 *            The same object that was returned by
		 *            {@link #instantiateItem(View, int)}.
		 */
		@Override
		public void destroyItem(View collection, int position, Object view) {
			((ViewPager) collection).removeView((View) view);
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == ((View) object);
		}

		/**
		 * Called when the a change in the shown pages has been completed. At
		 * this point you must ensure that all of the pages have actually been
		 * added or removed from the container as appropriate.
		 * 
		 * @param container
		 *            The containing View which is displaying this adapter's
		 *            page views.
		 */
		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}
	
	public class OnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {

        private int currentPage;

        @Override
        public void onPageSelected(int position) {
            currentPage = position;
			Var.cateID = currentPage;
			Var.store.setCateID(Var.cateID);
			
			LinearLayout ll = (LinearLayout) findViewById(R.id.title);
			switch (Var.cateID) {
			case Var.CHUYEN_AY:
				ll.setBackgroundResource(R.drawable.titlephongdoi);
				((ImageButton) findViewById(R.id.bt_ay)).setVisibility(View.GONE);
				((ImageButton) findViewById(R.id.bt_adam)).setVisibility(View.VISIBLE);
				((ImageButton) findViewById(R.id.bt_eva)).setVisibility(View.VISIBLE);
				
				if(Var.listChuyenAy.size() < 3){
					initQuestionList(Var.cateID);
				}
				break;
			case Var.CHUYEN_ADAM:
				ll.setBackgroundResource(R.drawable.titlephongnam);
				((ImageButton) findViewById(R.id.bt_ay)).setVisibility(View.VISIBLE);
				((ImageButton) findViewById(R.id.bt_adam)).setVisibility(View.GONE);
				((ImageButton) findViewById(R.id.bt_eva)).setVisibility(View.VISIBLE);
				
				if(Var.listChuyenAdam.size() < 3){
					initQuestionList(Var.cateID);
				}
				break;
			case Var.CHUYEN_EVA:
				ll.setBackgroundResource(R.drawable.titlephongnu);
				((ImageButton) findViewById(R.id.bt_ay)).setVisibility(View.VISIBLE);
				((ImageButton) findViewById(R.id.bt_adam)).setVisibility(View.VISIBLE);
				((ImageButton) findViewById(R.id.bt_eva)).setVisibility(View.GONE);
				
				if(Var.listChuyenEva.size() < 3){
					initQuestionList(Var.cateID);
				}
				break;
			}
        }

        public int getCurrentPage() {
            return currentPage;
        }
    }
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage("Loading...");
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(true);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}
	
	
	
	public void initQuestionList(final int cateID) {
		runOnUiThread(new Runnable() {
		    public void run() {
		    	if (!CommonUtils.isNetworkConnected(QuestionList.this)) {
					alert = new AlertDialog.Builder(QuestionList.this);
					alert.setMessage("Vui lòng kiểm tra lại kết nối mạng");
					alert.setPositiveButton("Thử lại",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									initQuestionList(cateID);
								}
							});
					alert.setNegativeButton("Thoát",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									QuestionList.this.finish();
									System.gc();
									android.os.Process.killProcess(android.os.Process.myPid());
								}
							});

					alert.setCancelable(true);
					alert.show(); 
					return;
				}
				
				try {
					// Tạo task kết nối với server
					new AsyncTask<Void, Void, String>() {
						@Override
						protected void onPreExecute() {
							// Hiển thị thông báo
							showDialog(0);
						}

						@Override
						protected String doInBackground(Void... arg0) {
							try {
								switch (cateID) {
								case Var.CHUYEN_ADAM:
									Var.listChuyenAdam = XMLParser.getCategoryList(Var.DATA_LINK + "services/appServer.php?index=content&appid=" + Var.APP_ID + "&level=2&cateid=2");
									break;
								case Var.CHUYEN_EVA:
									Var.listChuyenEva = XMLParser.getCategoryList(Var.DATA_LINK + "services/appServer.php?index=content&appid=" + Var.APP_ID + "&level=2&cateid=3");
									break;
								case Var.CHUYEN_AY:
									Var.listChuyenAy = XMLParser.getCategoryList(Var.DATA_LINK + "services/appServer.php?index=content&appid=" + Var.APP_ID + "&level=2&cateid=4");
									break;
								}

							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								System.out.println("Không kết nối được đến server 2");
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								System.out.println("Không kết nối được đến server 3");
							}
							return "";
						}

						// Hoàn thành truy vấn
						@Override
						protected void onPostExecute(String result) {
							
							viewPager.setAdapter(pagerAdapter);
							viewPager.setCurrentItem(Var.cateID);
							try {
								dismissDialog(0);
							} catch (Exception e) {
								// TODO: handle exception
							}
						}
					}.execute();
				} catch (Exception e) {
				}
		    }
		});
		
	}

	public void createAboutMessage() {
		alert = new AlertDialog.Builder(this);
		alert.setMessage(R.string.about);
		alert.setPositiveButton("Góp ý",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						final Intent emailIntent = new Intent(
								android.content.Intent.ACTION_SEND);

						/* Fill it with Data */
						emailIntent.setType("plain/text");
						emailIntent.putExtra(
								android.content.Intent.EXTRA_EMAIL,
								new String[] { "support@ikame.vn" });
						emailIntent.putExtra(
								android.content.Intent.EXTRA_SUBJECT,
								"Ứng dụng - Chuyện ấy");
						emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
								"Nội dung: ");

						/* Send it off to the Activity-Chooser */
						startActivity(Intent.createChooser(emailIntent,
								"Send mail..."));
					}
				});

		alert.setNegativeButton("Đóng", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});
		alert.setCancelable(false);
		alert.show();
	}
}
